package com.uhylab.uhuvinetest.fragment;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.UHApplication;
import com.uhylab.uhuvinetest.activity.UHPhotoActivity;
import com.uhylab.uhuvinetest.adapter.UHHistory_List_Adapter;
import com.uhylab.uhuvinetest.base.UHBase;
import com.uhylab.uhuvinetest.base.UHBaseFragment;
import com.uhylab.uhuvinetest.bean.Bean;
import com.uhylab.uhuvinetest.bean.UserHistory;
import com.uhylab.uhuvinetest.dao.CloudHistory;
import com.uhylab.uhuvinetest.dao.CloudHistoryDao;
import com.uhylab.uhuvinetest.dao.DaoSingleton;
import com.uhylab.uhuvinetest.dao.LocalHistory;
import com.uhylab.uhuvinetest.dao.LocalHistoryDao;
import com.uhylab.uhuvinetest.utils.VolleySingleton;
import com.uhylab.uhuvinetest.utils.sharedpreutils.SharedPreUtils;
import com.zhy.autolayout.AutoLinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xyb on 15/12/4 at UHylab
 * <p/>
 * exchange by xyb on 16/6/2 at UHylab
 *
 * @version 1.0
 */
public class UHHistoryFragment extends UHBaseFragment implements View.OnClickListener {
    private ListView history_list;
    private RelativeLayout null_show;
    private UHHistory_List_Adapter uhHistory_list_adapter;
    private VolleySingleton volleySingleton;
    private List<CloudHistory> data;
    private CloudHistoryDao cloudHistoryDao;
    private LocalHistoryDao localHistoryDao;
    private List<Bean> list = new ArrayList<>();
    private Handler mHandler;
    private AutoLinearLayout rl_title;


    @Override
    public void onResume() {
        super.onResume();
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                initAdapter();
                if (data.size() != 0) {
                    rl_title.setVisibility(View.VISIBLE);
                } else {
                    rl_title.setVisibility(View.GONE);
                }
                return false;
            }
        });

        request();
        if (null_show.getVisibility() == View.VISIBLE) {
            rl_title.setVisibility(View.GONE);
        } else if (null_show.getVisibility() == View.GONE) {
            rl_title.setVisibility(View.VISIBLE);
        }

    }


    @Override
    public void initData() {
        cloudHistoryDao = DaoSingleton.getInstance().getCloudHistoryDao();
        localHistoryDao = DaoSingleton.getInstance().getLocalHistoryDao();
        volleySingleton = VolleySingleton.getVolleySingleton(UHApplication.gainContext());
        null_show.setOnClickListener(this);
        history_list.setEmptyView(null_show);
    }

//    private void request() {
//        StringRequest stringRequest = new StringRequest(Request.Method.POST, UHBase.historyRecord, new Response.Listener<String>() {
//            @Override
//            public void onResponse(final String response) {
//
//                Log.e("UHHistoryFragment", response);
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            cloudHistoryDao.deleteAll();
//                            Gson gson = new Gson();
//                            UserHistory mUserHistory = gson.fromJson(response, UserHistory.class);
//                            data = mUserHistory.getData();
//                            for (int i = 0; i < data.size(); i++) {
//                                if (data.get(i).getDate() != null) {
//
//                                    cloudHistoryDao.insertOrReplace(data.get(i));
//                                }
//                            }
//                            List<LocalHistory> localHistories = localHistoryDao.loadAll();
//
//                            if (localHistories != null && localHistories.size() > 0) {
//                                for (int i = 0; i < localHistories.size(); i++) {
//                                    if (localHistories.get(i).getDate() != null) {
//
//                                        Bean bean = new Bean();
//                                        CloudHistory cloudHistory = new CloudHistory();
//                                        //日期
//                                        cloudHistory.setDate(localHistories.get(i).getDate());
//                                        bean.setDate(localHistories.get(i).getDate());
//                                        //胆红素
//                                        cloudHistory.setBilirubin(localHistories.get(i).getBilirubin());
//                                        cloudHistory.setBilirubin_status(localHistories.get(i).getBilirubin_status());
//                                        bean.setPoint8(Float.parseFloat(localHistories.get(i).getBilirubin()));
//                                        //抗坏血酸
//                                        cloudHistory.setAscorbicacid(localHistories.get(i).getAscorbicacid());
//                                        cloudHistory.setAscorbicacid_status(localHistories.get(i).getAscorbicacid_status());
//                                        bean.setPoint10(Float.parseFloat(localHistories.get(i).getAscorbicacid()));
//
//                                        cloudHistory.setTelephone(localHistories.get(i).getTelephone());
//                                        //比重
//                                        cloudHistory.setGravity_status(localHistories.get(i).getGravity_status());
//                                        cloudHistory.setGravity(localHistories.get(i).getGravity());
//                                        bean.setPoint6(Float.parseFloat(localHistories.get(i).getGravity()));
//                                        //潜血
//                                        cloudHistory.setBlood(localHistories.get(i).getBlood());
//                                        cloudHistory.setBlood_status(localHistories.get(i).getBlood_status());
//                                        bean.setPoint5(Float.parseFloat(localHistories.get(i).getBlood()));
//                                        //葡萄糖
//                                        cloudHistory.setGlucose(localHistories.get(i).getGlucose());
//                                        cloudHistory.setGlucose_status(localHistories.get(i).getGlucose_status());
//                                        bean.setPoint9(Float.parseFloat(localHistories.get(i).getGlucose()));
//                                        //酮体
//                                        cloudHistory.setKetones(localHistories.get(i).getKetones());
//                                        cloudHistory.setKetones_status(localHistories.get(i).getKetones_status());
//                                        bean.setPoint7(Float.parseFloat(localHistories.get(i).getKetones()));
//                                        //白细胞
//                                        cloudHistory.setLeukocytes(localHistories.get(i).getLeukocytes());
//                                        cloudHistory.setLeukocytes_status(localHistories.get(i).getLeukocytes_status());
//                                        bean.setPoint0(Float.parseFloat(localHistories.get(i).getLeukocytes()));
//                                        //亚硝酸盐
//                                        cloudHistory.setNitrite(localHistories.get(i).getNitrite());
//                                        cloudHistory.setNitrite_status(localHistories.get(i).getNitrite_status());
//                                        bean.setPoint1(Float.parseFloat(localHistories.get(i).getNitrite()));
//                                        //酸碱度
//                                        cloudHistory.setPh(localHistories.get(i).getPh());
//                                        cloudHistory.setPh_status(localHistories.get(i).getPh_status());
//                                        bean.setPoint4(Float.parseFloat(localHistories.get(i).getPh()));
//                                        //蛋白质
//                                        cloudHistory.setProtein(localHistories.get(i).getProtein());
//                                        cloudHistory.setProtein_status(localHistories.get(i).getProtein_status());
//                                        bean.setPoint3(Float.parseFloat(localHistories.get(i).getProtein()));
//                                        //尿胆原
//                                        cloudHistory.setUrobilinogen(localHistories.get(i).getUrobilinogen());
//                                        cloudHistory.setUrobilinogen_status(localHistories.get(i).getUrobilinogen_status());
//                                        bean.setPoint2(Float.parseFloat(localHistories.get(i).getUrobilinogen()));
//
//                                        cloudHistoryDao.insertOrReplace(cloudHistory);
//                                        list.add(bean);
//
//                                        if (null_show.getVisibility() == View.VISIBLE) {
//                                            rl_title.setVisibility(View.GONE);
//                                        } else {
//                                            rl_title.setVisibility(View.VISIBLE);
//                                        }
//
//                                    }
//
//                                }
//                            }
//
//                            mHandler.sendEmptyMessage(0);
//
//                        } catch (Exception e) {
//                            null_show.post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    Toast.makeText(mActivity, "获取历史记录失败", Toast.LENGTH_SHORT).show();
//                                }
//                            });
//
//                        }
//
//                    }
//                }).start();
//
//            }
//
//
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                List<LocalHistory> localHistories = localHistoryDao.loadAll();
//                cloudHistoryDao.deleteAll();
//                if (localHistories != null && localHistories.size() > 0)
//                    for (int i = 0; i < localHistories.size(); i++) {
//                        CloudHistory cloudHistory = new CloudHistory();
//                        cloudHistory.setDate(localHistories.get(i).getDate());
//                        cloudHistory.setBilirubin(localHistories.get(i).getBilirubin());
//                        cloudHistory.setBilirubin_status(localHistories.get(i).getBilirubin_status());
//                        cloudHistory.setAscorbicacid(localHistories.get(i).getAscorbicacid());
//                        cloudHistory.setAscorbicacid_status(localHistories.get(i).getAscorbicacid_status());
//                        cloudHistory.setTelephone(localHistories.get(i).getTelephone());
//                        cloudHistory.setGravity_status(localHistories.get(i).getGravity_status());
//                        cloudHistory.setGravity(localHistories.get(i).getGravity());
//                        cloudHistory.setBlood(localHistories.get(i).getBlood());
//                        cloudHistory.setBlood_status(localHistories.get(i).getBlood_status());
//                        cloudHistory.setGlucose(localHistories.get(i).getGlucose());
//                        cloudHistory.setGlucose_status(localHistories.get(i).getGlucose_status());
//                        cloudHistory.setKetones(localHistories.get(i).getKetones());
//                        cloudHistory.setKetones_status(localHistories.get(i).getKetones_status());
//                        cloudHistory.setLeukocytes(localHistories.get(i).getLeukocytes());
//                        cloudHistory.setLeukocytes_status(localHistories.get(i).getLeukocytes_status());
//                        cloudHistory.setNitrite(localHistories.get(i).getNitrite());
//                        cloudHistory.setNitrite_status(localHistories.get(i).getNitrite_status());
//                        cloudHistory.setPh(localHistories.get(i).getPh());
//                        cloudHistory.setPh_status(localHistories.get(i).getPh_status());
//                        cloudHistory.setProtein(localHistories.get(i).getProtein());
//                        cloudHistory.setProtein_status(localHistories.get(i).getProtein_status());
//                        cloudHistory.setUrobilinogen(localHistories.get(i).getUrobilinogen());
//                        cloudHistory.setUrobilinogen_status(localHistories.get(i).getUrobilinogen_status());
//                        cloudHistoryDao.insertOrReplace(cloudHistory);
//                    }
//                initAdapter();
//            }
//        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                Map<String, String> params = new HashMap<String, String>();
//                String tel = SharedPreUtils.getString(mActivity, "user_tel", "");
//                params.put("telephone", tel);
//                return params;
//            }
//        };
//        if (SharedPreUtils.getBoolean(getContext(), "is_Login", false)) {
//            volleySingleton.addQueue(stringRequest, "stgRequest");
//        }
//
//    }


    private void request() {
        String userToken = SharedPreUtils.getString(mActivity, "user_token", null);
        int offset = 0;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, UHBase.newHistoryRecord
                + "token=" + userToken + "&offset=" + offset + "&tag=0"
                , new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
//                Log.e("UHHistoryFragment", response);

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.getString("code");
                    if (code.equals("0000")) {
                        initDateHis(response);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }


        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                List<LocalHistory> localHistories = localHistoryDao.loadAll();
                cloudHistoryDao.deleteAll();
                if (localHistories != null && localHistories.size() > 0)
                    for (int i = 0; i < localHistories.size(); i++) {
                        CloudHistory cloudHistory = new CloudHistory();
                        cloudHistory.setCreatetime(localHistories.get(i).getDate());
                        cloudHistory.setBilirubin(localHistories.get(i).getBilirubin());
                        cloudHistory.setBilirubin_status(localHistories.get(i).getBilirubin_status());
                        cloudHistory.setAscorbicacid(localHistories.get(i).getAscorbicacid());
                        cloudHistory.setAscorbicacid_status(localHistories.get(i).getAscorbicacid_status());
                        cloudHistory.setTelephone(localHistories.get(i).getTelephone());
                        cloudHistory.setGravity_status(localHistories.get(i).getGravity_status());
                        cloudHistory.setGravity(localHistories.get(i).getGravity());
                        cloudHistory.setBlood(localHistories.get(i).getBlood());
                        cloudHistory.setBlood_status(localHistories.get(i).getBlood_status());
                        cloudHistory.setGlucose(localHistories.get(i).getGlucose());
                        cloudHistory.setGlucose_status(localHistories.get(i).getGlucose_status());
                        cloudHistory.setKetones(localHistories.get(i).getKetones());
                        cloudHistory.setKetones_status(localHistories.get(i).getKetones_status());
                        cloudHistory.setLeukocytes(localHistories.get(i).getLeukocytes());
                        cloudHistory.setLeukocytes_status(localHistories.get(i).getLeukocytes_status());
                        cloudHistory.setNitrite(localHistories.get(i).getNitrite());
                        cloudHistory.setNitrite_status(localHistories.get(i).getNitrite_status());
                        cloudHistory.setPh(localHistories.get(i).getPh());
                        cloudHistory.setPh_status(localHistories.get(i).getPh_status());
                        cloudHistory.setProtein(localHistories.get(i).getProtein());
                        cloudHistory.setProtein_status(localHistories.get(i).getProtein_status());
                        cloudHistory.setUrobilinogen(localHistories.get(i).getUrobilinogen());
                        cloudHistory.setUrobilinogen_status(localHistories.get(i).getUrobilinogen_status());
                        cloudHistoryDao.insertOrReplace(cloudHistory);
                    }
                initAdapter();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                String tel = SharedPreUtils.getString(mActivity, "user_tel", "");
                params.put("telephone", tel);
                return params;
            }
        };
        if (SharedPreUtils.getBoolean(getContext(), "is_Login", false)) {
            volleySingleton.addQueue(stringRequest, "stgRequest");
        }

    }

    private void initDateHis(final String response) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    cloudHistoryDao.deleteAll();
                    Gson gson = new Gson();
                    UserHistory mUserHistory = gson.fromJson(response, UserHistory.class);
                    data = mUserHistory.getData();
//                    Log.e("UHHistoryFragment", "data.size():" + data.size());
                    for (int i = 0; i < data.size(); i++) {
                        if (data.get(i).getCreatetime() != null) {
                            cloudHistoryDao.insertOrReplace(data.get(i));
                        }
                    }
                    List<LocalHistory> localHistories = localHistoryDao.loadAll();

                    if (localHistories != null && localHistories.size() > 0) {
                        for (int i = 0; i < localHistories.size(); i++) {
                            if (localHistories.get(i).getDate() != null) {

                                Bean bean = new Bean();
                                CloudHistory cloudHistory = new CloudHistory();
                                //日期
                                cloudHistory.setCreatetime(localHistories.get(i).getDate());
                                bean.setDate(localHistories.get(i).getDate());
                                //胆红素
                                cloudHistory.setBilirubin(localHistories.get(i).getBilirubin());
                                cloudHistory.setBilirubin_status(localHistories.get(i).getBilirubin_status());
                                bean.setPoint8(Float.parseFloat(localHistories.get(i).getBilirubin()));
                                //抗坏血酸
                                cloudHistory.setAscorbicacid(localHistories.get(i).getAscorbicacid());
                                cloudHistory.setAscorbicacid_status(localHistories.get(i).getAscorbicacid_status());
                                bean.setPoint10(Float.parseFloat(localHistories.get(i).getAscorbicacid()));

                                cloudHistory.setTelephone(localHistories.get(i).getTelephone());
                                //比重
                                cloudHistory.setGravity_status(localHistories.get(i).getGravity_status());
                                cloudHistory.setGravity(localHistories.get(i).getGravity());
                                bean.setPoint6(Float.parseFloat(localHistories.get(i).getGravity()));
                                //潜血
                                cloudHistory.setBlood(localHistories.get(i).getBlood());
                                cloudHistory.setBlood_status(localHistories.get(i).getBlood_status());
                                bean.setPoint5(Float.parseFloat(localHistories.get(i).getBlood()));
                                //葡萄糖
                                cloudHistory.setGlucose(localHistories.get(i).getGlucose());
                                cloudHistory.setGlucose_status(localHistories.get(i).getGlucose_status());
                                bean.setPoint9(Float.parseFloat(localHistories.get(i).getGlucose()));
                                //酮体
                                cloudHistory.setKetones(localHistories.get(i).getKetones());
                                cloudHistory.setKetones_status(localHistories.get(i).getKetones_status());
                                bean.setPoint7(Float.parseFloat(localHistories.get(i).getKetones()));
                                //白细胞
                                cloudHistory.setLeukocytes(localHistories.get(i).getLeukocytes());
                                cloudHistory.setLeukocytes_status(localHistories.get(i).getLeukocytes_status());
                                bean.setPoint0(Float.parseFloat(localHistories.get(i).getLeukocytes()));
                                //亚硝酸盐
                                cloudHistory.setNitrite(localHistories.get(i).getNitrite());
                                cloudHistory.setNitrite_status(localHistories.get(i).getNitrite_status());
                                bean.setPoint1(Float.parseFloat(localHistories.get(i).getNitrite()));
                                //酸碱度
                                cloudHistory.setPh(localHistories.get(i).getPh());
                                cloudHistory.setPh_status(localHistories.get(i).getPh_status());
                                bean.setPoint4(Float.parseFloat(localHistories.get(i).getPh()));
                                //蛋白质
                                cloudHistory.setProtein(localHistories.get(i).getProtein());
                                cloudHistory.setProtein_status(localHistories.get(i).getProtein_status());
                                bean.setPoint3(Float.parseFloat(localHistories.get(i).getProtein()));
                                //尿胆原
                                cloudHistory.setUrobilinogen(localHistories.get(i).getUrobilinogen());
                                cloudHistory.setUrobilinogen_status(localHistories.get(i).getUrobilinogen_status());
                                bean.setPoint2(Float.parseFloat(localHistories.get(i).getUrobilinogen()));

                                cloudHistoryDao.insertOrReplace(cloudHistory);
                                list.add(bean);

                                if (null_show.getVisibility() == View.VISIBLE) {
                                    rl_title.setVisibility(View.GONE);
                                } else {
                                    rl_title.setVisibility(View.VISIBLE);
                                }
                            }

                        }
                    }

                    mHandler.sendEmptyMessage(0);

                } catch (Exception e) {
                    null_show.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mActivity, "获取历史记录失败", Toast.LENGTH_SHORT).show();
                        }
                    });

                }

            }
        }).start();
    }

    private void initAdapter() {
        uhHistory_list_adapter = new UHHistory_List_Adapter(mActivity, cloudHistoryDao.loadAll());
        history_list.setAdapter(uhHistory_list_adapter);
    }

    @Override
    protected void initDestrory() {

    }

    @Override
    protected void initView() {
        history_list = (ListView) view.findViewById(R.id.history_list);
        null_show = (RelativeLayout) view.findViewById(R.id.null_show);
        rl_title = (AutoLinearLayout) view.findViewById(R.id.rl_title);


    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container) {
        view = inflater.inflate(R.layout.fragment_history, null);
        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.null_show:
                Intent intent = new Intent(getContext(), UHPhotoActivity.class);
                startActivity(intent);
                break;
        }
    }

    public void toLastTest(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = null;
        try {
            parse = sdf.parse(date);
            DateFormat data = new SimpleDateFormat("yyyy年MM月dd日");
            DateFormat time = new SimpleDateFormat("HH:mm");
            String format = data.format(parse);
            String format1 = time.format(parse);
            TextView history_date = new TextView(mActivity);
            TextView history_time = new TextView(mActivity);
            history_date.setText(format);
            history_time.setText(format1);
            uhHistory_list_adapter.fisss(0, history_date, history_time,true);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
